import os
import time

import requests
from uuid import uuid4
from setting import MONGODB, COVER_PATH, MUSIC_PATH

id = "424529"
url = f"https://www.ximalaya.com/revision/play/album?albumId={id}&pageNum=1&sort=1&pageSize=30"
headers = {
	"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36"
}
res = requests.get(url, headers=headers)
# print(res.text)
# print(res.content)
xmly_content = res.json()
res_content_list = xmly_content.get("data").get("tracksAudioPlay")
content_li = []
for content_info in res_content_list:
	title = content_info.get("trackName")
	filename = f"{uuid4()}"
	music_name = f"{filename}.mp3"
	cover_name = f"{filename}.jpg"

	audio_data = requests.get(content_info.get("src"))
	with open(f"{os.path.join(MUSIC_PATH,music_name)}", "wb") as mf:
		mf.write(audio_data.content)

	cover_data = requests.get(f"http:{content_info.get('trackCoverPath')}")
	with open(f"{os.path.join(COVER_PATH,cover_name)}", "wb") as cf:
		cf.write(cover_data.content)

	music_info = {
		"music": music_name,
		"cover": cover_name,
		"title": title
	}
	content_li.append(music_info)
	time.sleep(0.5)

MONGODB.content.insert_many(content_li)